package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.order.domain.OrderInfo;
import com.spzx.order.domain.OrderItem;
import com.spzx.order.form.OrderForm;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.service.IOrderInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.order.vo.TradeVo;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.RemoteSkuStockService;
import com.spzx.product.api.vo.ProductSkuVo;
import com.spzx.product.api.vo.SkuLockVo;
import com.spzx.product.api.vo.SkuPriceVo;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.api.domain.UserAddress;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author Login
 * @since 2025-07-27
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RemoteCartService remoteCartService;
    @Autowired
    private RemoteUserAddressService remoteUserAddressService;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private RemoteProductService remoteProductService;
    @Autowired
    private RemoteSkuStockService remoteSkuStockService;
    @Autowired
    private RabbitService rabbitService;

    @Override
    public TradeVo orderTradeData() {
        //获取当前登录用户的id
        Long userId = SecurityContextHolder.getUserId();
        R<List<CartInfo>> cartInfoListResult = remoteCartService.getCartCheckedList(SecurityConstants.INNER);
        if (R.FAIL == cartInfoListResult.getCode()){
            throw new ServiceException(cartInfoListResult.getMsg());
        }
        List<CartInfo> cartInfoList = cartInfoListResult.getData();
        if (CollectionUtils.isEmpty(cartInfoList)){  //健壮性判断，判断购物车里是否有商品
            throw new ServiceException("请选择商品");
        }
        ArrayList<OrderItem> orderItemList = new ArrayList<>();
        for (CartInfo cartInfo : cartInfoList){
            OrderItem orderItem =new OrderItem();
            BeanUtils.copyProperties(cartInfo,orderItem);
            orderItemList.add(orderItem);
        }
        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setIsBuy(false);//不是立即购买

        //总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            System.out.println("商品价格: " + orderItem.getSkuPrice() + ", 数量: " + orderItem.getSkuNum());
            BigDecimal multiply = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum()));
            totalAmount = totalAmount.add(multiply);
        }
/*       // 添加校验逻辑
        if (totalAmount.compareTo(BigDecimal.ZERO) <= 0 && !CollectionUtils.isEmpty(cartInfoList)) {
            // 如果总金额为0但购物车不为空，则重新计算或抛出异常
            throw new ServiceException("金额计算异常，请重新尝试");
        }*/
        System.out.println("总金额: " + totalAmount);
        tradeVo.setTotalAmount(totalAmount);
        String tradeNo = generateTradeNo();
        tradeVo.setTradeNo(tradeNo); //订单号，防止订单号重复
        return tradeVo;
    }

    @Override
    public Long submitOrder(OrderForm orderForm) {
        //1 todo  防止订单重复提交&防止页面停留超时
        /*方式一：
        if(!checkTrandNo(orderForm.getTradeNo())){ //checkTradeNo返回false，表示订单号被删除了，就提示用户，不要重复提交订单
            throw new ServiceException("订单已提交，请勿重复提交");
        }
        //checkTradeNo返回true,表示订单号没有被删除，那就删除订单号
        deleteTradeNo();
*/
        //方式二：
        Long userId = SecurityUtils.getUserId();//获取当前登录用户的id
        String userTradeKey = "user:tradeNo:" + userId;//构建订单流水号
        // 将键的值更为 processed  表示已处理
        // return 1 表示处理成功
        // return -1  键存在但值不匹配，表示重复提交
        // return 0   键不存在，订单过期
        String scriptText = """
                if redis.call('get',KEYS[1])== ARGV[1] then
                redis.call('set',KEYS[1],'processed','ex',ARGV[2])
                return 1
                else
                    if redis.call('exists',KEYS[1])== 1 then
                    return -1
                    else
                        return 0
                    end
                end
                """;
        DefaultRedisScript<Long> redisScript =new DefaultRedisScript<>();
        redisScript.setScriptText(scriptText); //给redisScript设置核心脚本
        redisScript.setResultType(Long.class); //参数返回值类型是long型
                                //      todo     lua脚本，参数1：redisScript，参数2：key1,key2... 参数3：argv[1]、argv[2]...，参数4：过期时间
        Long flag = (Long)redisTemplate.execute(redisScript, Arrays.asList(userTradeKey),orderForm.getTradeNo(),3);
        if (flag == 0){
            throw new ServiceException("操作超时，请退回重试");
        }
        if (flag == -1){
            throw new ServiceException("订单已提交，请勿重复提交");
        }

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        //2 判断价格是否改变并更新购物车中的价格
        //2.1 批量获取实时商品价格
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        ////获取商品skuid列表
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).collect(Collectors.toList());
        //获取购物车商品的实时价格
        R<List<SkuPriceVo>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if (R.FAIL == skuPriceListResult.getCode()){
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPriceVo> skuPriceVoList = skuPriceListResult.getData();

        //2.2 并判断价格是否变更
        //将skuId和实时价格封装成map
        //获取那些价格发生了变化
        String priceCheckResult = "";
        Map<Long, BigDecimal> priceMap = skuPriceVoList.stream().collect(Collectors.toMap(SkuPriceVo::getSkuId, SkuPriceVo::getSalePrice));
        for (OrderItem orderItem : orderItemList){
            Long skuId = orderItem.getSkuId();
            if (orderItem.getSkuPrice().compareTo(priceMap.get(skuId)) != 0){
                priceCheckResult += orderItem.getSkuName() +"\n";
            }
        }
        //2.3 如果有变更，则更新购物车中的商品价格
        if (StringUtils.hasText(priceCheckResult)){
            if(!orderForm.getIsBuy()) {//如果是不立即购买，则更新购物车中的商品价格（从购物车中购买）
                //更新购物车中的商品价格
                R<Boolean> updateCartPriceResult = remoteCartService.updateCartPrice(SecurityConstants.INNER);//远程调用updateCartPrice方法
                if (R.FAIL == updateCartPriceResult.getCode()){
                    throw new ServiceException(updateCartPriceResult.getMsg());
                }
            }
            throw new ServiceException("价格有变动，请重新选择商品价格：");
        }

        //3 校验库存并锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map(orderItem -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            skuLockVo.setSkuName(orderItem.getSkuName());
            return skuLockVo;
        }).toList();

        R<String> checkAndLockResult = remoteSkuStockService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER);
        if (R.FAIL == checkAndLockResult.getCode()){
            throw new ServiceException(checkAndLockResult.getMsg());
        }
        String andLockResultData = checkAndLockResult.getData();
        if (StringUtils.isNotEmpty(andLockResultData)){ //如果不为空
            throw new ServiceException(andLockResultData);
        }

        //4 下单
        Long orderId = null;
        //下单异常时要解锁库存
        Long OrderId = null;
        try {
            OrderId = this.saveOrder(orderForm);
        } catch (Exception e) {
//            e.printStackTrace();
            //下单失败，解锁库存(异步 )
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK,orderForm.getTradeNo());
            log.error("下单失败："+ e);
            throw new ServiceException("下单失败");
        }

        //5 删除购物车中的选中商品
        if (!orderForm.getIsBuy()){
            R<Boolean> deleteResult = remoteCartService.deleteCartCheckedList(SecurityConstants.INNER);//表示这是微服务之间的内部请求
            if (R.FAIL == deleteResult.getCode()){
                log.error(deleteResult.getMsg());  //为了在保证核心业务成功的同时，不影响用户体验，并通过日志记录问题供后续处理。这是分布式系统中常见的错误处理策略。
            }
        }
        return OrderId;
    }

    @Override
    public TradeVo buy(Long skuId) {
        //2、 获取商品信息
        R<ProductSkuVo> productSkuVoResult = remoteProductService.getproductSku(skuId, SecurityConstants.INNER);
        if (R.FAIL == productSkuVoResult.getCode()){
            throw new ServiceException(productSkuVoResult.getMsg());
        }
        ProductSkuVo productSkuVo = productSkuVoResult.getData();
        //3、封装订单商品信息
        ArrayList<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(productSkuVo.getId());
        orderItem.setSkuName(productSkuVo.getSkuName());
        orderItem.setThumbImg(productSkuVo.getThumbImg());
        orderItem.setSkuPrice(productSkuVo.getSalePrice());
        orderItem.setSkuNum(1);
        orderItemList.add(orderItem);
        //1、
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(productSkuVo.getSalePrice());
        tradeVo.setTradeNo(generateTradeNo());
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setIsBuy(true);
        return tradeVo;
    }

    @Override
    public List<OrderInfo> selectUserOrderInfoList(Integer orderStatus) {
        LambdaQueryWrapper<OrderInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                .eq(OrderInfo::getUserId,SecurityUtils.getUserId()) //查询当前登录用户的订单
                .eq(orderStatus != null,OrderInfo::getOrderStatus,orderStatus)//只有当 orderStatus 不为 null 时才添加这个条件
                .orderByDesc(OrderInfo::getCreateTime);//按创建时间倒序排列（最新的在前(倒序)）
        //查询所有的订单列表
        List<OrderInfo> orderInfoList = baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(orderInfoList)){
            //订单主表和订单明细表的关联查询，将分散在两个表中的数据组装成完整的订单信息。
            //查询所有订单项列表
            LambdaQueryWrapper<OrderItem> queryWrapperItem = new LambdaQueryWrapper<>();
            queryWrapperItem.in(
                    OrderItem::getOrderId,  // 查询字段： 订单ID  todo 会查询所有的订单项
                    orderInfoList.stream().map(OrderInfo::getId).toList()); // 订单ID列表
            List<OrderItem> orderItemList = orderItemMapper.selectList(queryWrapperItem);

            //将订单项列表根据订单id进行分组到相对应的订单对象中
            //生成一个 Map，key 是订单ID，value 是该订单的所有订单项列表
            Map<Long, List<OrderItem>> listMap = orderItemList
                    .stream()
                    .collect(Collectors.groupingBy(OrderItem::getOrderId));//将所有订单项按照 orderId 进行分组
            //数据组装
            for (OrderInfo orderInfo : orderInfoList){
                orderInfo.setOrderItemList(listMap.get(orderInfo.getId()));
            }
            return orderInfoList;
        }
        return new ArrayList<OrderInfo>(); //没有就返回空数据
    }

    @Override
    public OrderInfo getOrderInfoById(Long orderId) {
        //根据orderId获取订单项
        LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItem::getOrderId, orderId);
        List<OrderItem> orderItemList = orderItemMapper.selectList(queryWrapper);

        OrderInfo orderInfo = baseMapper.selectById(orderId);
        orderInfo.setOrderItemList(orderItemList);

        return orderInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelOrder(Long orderId) {
        OrderInfo orderInfo = baseMapper.selectById(orderId);
        orderInfo.setOrderStatus(-1);//已取消
        orderInfo.setCancelTime(new Date());
        orderInfo.setCancelReason("用户取消订单");
        baseMapper.updateById(orderInfo);
        //发送MQ消息通知商品系统解锁库存：TODO
        rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK,orderInfo.getOrderNo());



    }

    private Long saveOrder(OrderForm orderForm) {
        Long userId =  SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        //保存订单记录：order_info
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setUserId(userId);
        orderInfo.setNickName(username);
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setFeightFee(orderForm.getFeightFee());
        orderInfo.setRemark(orderForm.getRemark());

        Long userAddressId = orderForm.getUserAddressId();//用户地址id
        R<UserAddress> userAddressResult = remoteUserAddressService.getUserAddress(userAddressId, SecurityConstants.INNER);//远程调用获取用户地址
        if (R.FAIL==userAddressResult.getCode()){
            throw new ServiceException(userAddressResult.getMsg());
        }
        UserAddress userAddress = userAddressResult.getData(); //上面4排内容获取userAddressResult。这里获取userAddressResult里的数据
        //保存用户地址信息
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        //订单总金额
        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);
        orderInfo.setCouponAmount(BigDecimal.ZERO);
        orderInfo.setOriginalTotalAmount(totalAmount);
        orderInfo.setOrderStatus(0);//待付款

        orderInfo.setCreateBy(username);
        orderInfo.setUpdateBy(username);
        baseMapper.insert(orderInfo);// 插入订单主表，此时会生成ID  调用MyBatis-Plus提供的基础Mapper方法，将订单信息插入到数据库中

        //保存订单项记录：order_item
        for (OrderItem orderItem : orderItemList) {
            orderItem.setCreateBy(username);
            orderItem.setUpdateBy(username);
            orderItem.setOrderId(orderInfo.getId());
            orderItemMapper.insert(orderItem);
        }

        return orderInfo.getId(); // 返回新创建的订单ID   让调用方（submitOrder 方法）能够获取到新创建的订单编号、用于后续的业务流程处理

    }



    private String generateTradeNo() {
        Long userId = SecurityUtils.getUserId();
        //1.构建流水号Key
        String userTradeKey = "user:tradeNo:" + userId;
        //2.构建流水号value
        String tradeNo = UUID.randomUUID().toString().replace("-","");
        //3.将流水号存入Redis 暂存5分钟
        redisTemplate.opsForValue().set(userTradeKey,tradeNo,5, TimeUnit.SECONDS);
        return tradeNo;
    }
    /*
     * 验证页面流水号是否有效
     * */
    private boolean checkTrandNo(String tradeNo){
        Long userId = SecurityUtils.getUserId();
        String userTrandeKey = "user:tradeNo:"+userId;//构建流水号Key
        String  tradeNoRedis = (String)redisTemplate.opsForValue().get(userTrandeKey);
        return tradeNoRedis.equals(tradeNo);  //如果返回false 则订单流水被删除，订单已经提交；返回true，说明订单流水未删除，订单未提交
    }
    /**
     * 删除流水号(redis里的)
     *
     */
    private void deleteTradeNo() {
        Long userId = SecurityUtils.getUserId();
        String userTrandeKey = "user:tradeNo:"+userId;
        redisTemplate.delete(userTrandeKey);
    }


}
